var app = getApp()
var util = require('../../../utils/util.js');
var netWork = require('../../../utils/netutil.js');
var config = require('../../../utils/config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    trainInfo:null,//火车票信息
    cabinInfo:null,//座位信息
    fromCity:null,
    goCity:null,
    goDate:'',
    goWeek:'',
    arriveDate:'',
    arriveWeek:'',
    passengerArr: new Array(),//乘机人
    approveArr: new Array(),//审批人
    reasonStr: '',
    linkMan: '',
    payType: 0,//支付方式。默认勾选公司支付
    showDetail: false,//是否显示明细，默认不显示
    showInsurance: false,//是否显示保险,默认不显示
    linkManInfo: new Object(),//联系人信息
    onBusinessReason: '',//出差原因
    insuranceArr: new Array(),//保险数组
    insuranceMid: new Array(),//保险勾选中间替换数组
    SettlementType: 1,//订单结算方式(1个人：现付 2公司：预存款)默认为公司支付1.
    checkCompany: true,//公司支付
    checkSelf: false,//个人支付
    standardAlertReason:'',//差标继续预定原因
    IsOverStandard:false,
    totalMoney:0,
    showApproveView: true,//是否需要审批
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var trainInfo = JSON.parse(options.trainInfo);
    var cabinInfo = JSON.parse(options.cabinInfo);
    var arriveDate = util.getDate(trainInfo.ATime, true, false);
    var arriveDateStr = util.getMMDD(util.getDate(trainInfo.ATime, true, false));
    var arriveWeek = util.getTheDateWeek(arriveDate);

    that.data.standardAlertReason = options.standardAlertReason;
    that.data.IsOverStandard = options.IsOverStandard; 

    that.data.fromCity = JSON.parse(options.fromCity);
    that.data.toCity = JSON.parse(options.toCity);
    //获取保险
    that.loadTheUrlForInsuranceInfo();

    //联系人信息
    var name = app.globalData.TUserInfo.TrueName != null ? app.globalData.TUserInfo.TrueName : '';
    var phone = app.globalData.TUserInfo.UserName != null ? app.globalData.TUserInfo.UserName : '';
    var email = app.globalData.TUserInfo.Email != null ? app.globalData.TUserInfo.Email : '';
    that.data.linkManInfo.name = name;
    that.data.linkManInfo.phone = phone;
    that.data.linkManInfo.email = email;

    var showApproveView = app.globalData.TUserInfo.IsNeedTrainApprove;
    wx.setNavigationBarTitle({
      title: that.data.fromCity.Name + '-' + that.data.toCity.Name,
    })
    that.setData ({
      trainInfo: trainInfo,
      cabinInfo: cabinInfo,
      goDate: util.getMMDD(options.goDate),
      goWeek:options.goWeek,
      arriveDate:arriveDateStr,
      arriveWeek:arriveWeek,
      linkManInfo: that.data.linkManInfo,
      showApproveView: showApproveView,
    })
  },
  //请求保险接口获取保险数据
  loadTheUrlForInsuranceInfo: function () {
    var that = this;
    that.showLoading();

    var postDic = new Object();
    postDic.UserID = app.globalData.TUserInfo.UserID;//UserID


    var url = config.getBaseUrl('Train', 'GetCreateOrderParameters');
    netWork.post(
      url,
      postDic,
      function (res) {//success
        wx.hideLoading()
        console.log('火车票下单参数')
        console.log(res.data);
        var insuranceArr = res.data.Data.InsuranceProduct.DataProduct;
        for (var i = 0; i < insuranceArr.length; i++) {
          insuranceArr[i].select = false;
        }
        var serFee = res.data.Data.SerFee;
        //刷新列表
        that.setData({
          insuranceArr: insuranceArr,
          SerFee:serFee,
        })
      },
      function (res) {//fail
        wx.hideLoading()
      }
    )
  },
  //show request loading..
  showLoading: function () {
    wx.showLoading({
      title: '加载中...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 6000)
  },
  /**
   * {"RequestMetaInfo":{"SiteId":1,"TimeSpan":1,"Sign":1},"Data":{"UserID":39,"SiteID":1,"OrderFromTerminal":5,"TravelType":0,"SettlementType":2,"TravelReason":"","OrderAmount":553,"StartCity":"上海","EndCity":"北京","TrainNo":"G146","StartTime":"2017-09-15 15:05:00","EndTime":"2017-09-15 20:51:00","Remark":"","IsOverStandard":false,"OverStandardRemark":"","ContactName":"姚明","ContactMobile":"17621555911","ContactEmail":"","LstApproveUserIDs":[39],"OrderPsg":[{"PsgName":"倪星","TicketType":"成人","SeatType":"二等座(553.00元)","CardType":0,"CardNo":"342921199008163413","Phone":"","TicketPrice":"553.00","IsuProductCode":""}]}}
   */
  //创建请求列表数据所需的postDic
  preparePostDic: function () {
    var that = this;
    var postDic = new Object();
    var totalMoney = that.calculateTheTotalMoney();
    //1.base info
    postDic.UserID = app.globalData.TUserInfo.UserID;////下单者用户ID 即企业员工
    postDic.SiteID = 10;
    postDic.OrderFromTerminal = 5;// 订单来源终端(0 OA导单 1企业差旅前台  2安卓客户端   3苹果客户端  4 H5   5 微信小程序 9 其他 )
    postDic.TravelType = 0;/// 差旅类型 (对应枚举TravelType值 0因公 , 1因私 ) 。 （必填）
    postDic.SettlementType = that.data.checkCompany == true ? 2 : 1;//订单结算方式（对应枚举SettlementType值 1个人：现付 2公司：预存款 3月结） 
    postDic.TravelReason = that.data.onBusinessReason; //出差事由
    postDic.OrderAmount = that.data.totalMoney; //订单总金额(所有金额之和)
    postDic.StartCity = that.data.fromCity.Name;
    postDic.EndCity = that.data.toCity.Name;
    postDic.TrainNo = that.data.trainInfo.TrainID;//车次
    postDic.StartTime = that.data.trainInfo.DTime.split('/').join('-');//出发时间
    postDic.EndTime = that.data.trainInfo.ATime.split('/').join('-');//到达时间
    postDic.Remark = '';//备注
    postDic.IsOverStandard = that.data.IsOverStandard;//是否超标
    postDic.OverStandardRemark = that.data.standardAlertReason;//超标备注
    postDic.ContactName = that.data.linkManInfo.name; ////联系人姓名
    postDic.ContactPhone = that.data.linkManInfo.phone;//联系人手机号
    postDic.ContactEmail = that.data.linkManInfo.email; //联系人 邮箱（选填）

    //审批人
    var approveArr = new Array();
    for (var i = 0; i < that.data.approveArr.length; i++) {
      var id = that.data.approveArr[i].UserID;
      approveArr.push(id);
    }
    postDic.LstApproveUserIDs = approveArr;

    //乘机人信息
    //4.乘机人
    var passengerArr = new Array();
    for (var i = 0; i < that.data.passengerArr.length; i++) 
    {
      console.log('that. passengerArr');
      console.log(that.data.passengerArr);
      
      var passengerDic = new Object();
      passengerDic.PsgName = that.data.passengerArr[i].CName;
      passengerDic.TicketType = '成人';
      passengerDic.SeatType = that.data.cabinInfo.name + '(' + that.data.cabinInfo.price + '元)'
      passengerDic.CardType = that.data.passengerArr[i].CardType;
      passengerDic.CardNo = that.data.passengerArr[i].CardNo;
      passengerDic.Phone = that.data.passengerArr[i].Mobie == null ? '' : that.data.passengerArr[i].Mobie;
      passengerDic.TicketPrice = that.data.cabinInfo.price;

      //保险..
      var insuranceStr = '';
      var spaceStr = '';
      for (var j = 0; j < that.data.insuranceArr.length; j++) {
        if (that.data.insuranceArr[j].select == true) {
          if(insuranceStr.length == 0) {
            spaceStr = '';
          }else {
            spaceStr = ',';
          }
          insuranceStr = insuranceStr + spaceStr +  that.data.insuranceArr[j].ProductCode;
        }
      }
      passengerDic.IsuProductCode = insuranceStr;
      passengerArr.push(passengerDic);
    }
    console.log('passengerArr');
    console.log(passengerArr);
    postDic.OrderPsg = passengerArr;
    console.log('postDic:');
    console.log(postDic);
    return postDic;
  },
  //计算总价
  calculateTheTotalMoney: function () {
    var that = this;
    var totalMoney = 0;
    //乘机人(全部为成人,人数直接相乘)
    var passengerCount = that.data.passengerArr.length;

    //票价
    var ticketPrice = that.data.cabinInfo.price;
    ticketPrice = (ticketPrice) * passengerCount;

    //服务费
    var serFee = that.data.SerFee;
    serFee = serFee * passengerCount;

    //保险费
    var insurancePrice = 0;
    var insuranceP = 0;
    var insuranceArr = that.data.insuranceArr;
    for (var i = 0; i < insuranceArr.length; i++) {
      if (insuranceArr[i].select == true) {
        insuranceP = insuranceP + insuranceArr[i].SalePrice;
      }
    }

    console.log('保险费......');
    console.log(insuranceArr);
    console.log(insuranceP);
    insurancePrice = insuranceP * passengerCount;
    console.log('1:' + ticketPrice + '3:' + insurancePrice);
    totalMoney = ticketPrice + insurancePrice + serFee;

    that.setData({
      totalMoney:totalMoney,
    })
    return totalMoney;
  },
  passenger: function () {
    //type:0火车票，1国内机票
    //选择乘机人页要求传值.
    app.globalData.tempData = that.data.passengerArr;
    wx.navigateTo({
      url: '../../passenger/passengerSelect/passengerSelect?type=' + 0,
    })
  },
  //显示明细
  showDetail: function (event) {
    var that = this;
    console.log(!that.data.showDetail);
    if (!that.data.showDetail) {//显示
      that.setupDetailInfo();
    }
    that.setData({
      showDetail: !that.data.showDetail,
    })
  },
  //明细信息
  setupDetailInfo: function () {
    var that = this;
    var totalMoney = 0;
    //乘机人(全部为成人,人数直接相乘)
    var passengerCount = that.data.passengerArr.length;

    //票价
    var ticketPrice = that.data.cabinInfo.price;

    //服务费:SerFee
    var serfee = that.data.SerFee;

    //保险费
    var insurancePrice = 0;
    var insuranceP = 0;
    var insuranceArr = that.data.insuranceArr;
    console.log('baoxian');
    console.log(insuranceArr);
    for (var i = 0; i < insuranceArr.length; i++) {
      if (insuranceArr[i].select == true) {
        insuranceP = insuranceP + insuranceArr[i].SalePrice;
      }
    }

    var detailInfoArr = new Array();
    var detailInfoDic = new Object();
    detailInfoDic.name = '成人票';
    detailInfoDic.priceStr = ticketPrice + 'x' + passengerCount;
    detailInfoArr.push(detailInfoDic);

    //保险费
    var serveArr = new Array();
    if (insuranceP > 0) {
      var insuranceDic = new Object();
      insuranceDic.name = '保险费';
      insuranceDic.priceStr = insuranceP + 'x' + passengerCount;
      serveArr.push(insuranceDic);
    }
    //服务费
    if (serfee > 0) {
      var serFeeDic = new Object();
      serFeeDic.name = '服务费';
      serFeeDic.priceStr = serfee + 'x' + passengerCount;
      serveArr.push(serFeeDic);
    }
    console.log(detailInfoArr);
    console.log(serveArr);
    console.log(insuranceP);
    console.log(serfee);
    that.setData({
      ticketDetailArr: detailInfoArr,
      serDetailArr: serveArr,
    })
  },
  //点击保险
  insuranceTap: function () {
    var that = this;
    //赋值
    that.data.insuranceMid = that.data.insuranceArr;
    that.setData({
      insuranceMid: that.data.insuranceMid,
      showInsurance: !that.data.showInsurance
    })
  },
  //点击了保险项..
  selectInsurance: function (res) {
    var that = this;
    var index = res.currentTarget.dataset.index;
    for(var i = 0;i < that.data.insuranceMid.length;i++) {
      that.data.insuranceMid[i].select = false;
    }
     that.data.insuranceMid[index].select = true;
     that.setData({
       insuranceMid: that.data.insuranceMid
     })
    console.log(index + ':' + that.data.insuranceMid[index].select);
  },
  //保险取消
  insuranceCancel: function () {
    var that = this;
    that.setData({
      showInsurance: false
    })
  },
  //保险确定
  insuranceSure: function () {
    var that = this;
    //确定中间值刷新数据源
    that.data.insuranceArr = that.data.insuranceMid;
    that.setData({
      showInsurance: false
    })
    var totalMoney = that.calculateTheTotalMoney();
  },
  ///选择乘机人回调函数
  updateData: function (res) {
    var that = this;
    console.log('乘机人');
    console.log(res);
    // for (var i = 0;i < res.length;i++) {
    //   that.data.passengerArr.push(res[i]);
    // }

    //刷新data
    that.setData({
      passengerArr: res,
    })
    var totalMoney = that.calculateTheTotalMoney();
  },
  //删除乘机人
  deleteMySelf: function (event) {
    var that = this;
    var index = event.currentTarget.dataset.index;
    console.log('delete');
    that.data.passengerArr.splice(index, 1);
    that.setData({
      passengerArr: that.data.passengerArr,
    })
    that.calculateTheTotalMoney();
  },

  /**
   * 选择审批人回调函数(approve)
   * res:审批人数组
   */
  updateApproveData: function (res) {
    var that = this;

    that.setData({
      approveArr: res,
    })
    var totalMoney = that.calculateTheTotalMoney();
  },
  //删除审批人
  deleteApprover:function(res) {
    var that = this;
    var index = res.currentTarget.dataset.index;
    that.data.approveArr.splice(index, 1);
    that.setData({
      approveArr: that.data.approveArr,
    })
  },
  //出差原因
  textChange: function (res) {
    var that = this;
    that.data.onBusinessReason = res.detail.value;
  },

  //选择乘机人
  passenger: function () {
    var that = this;
    //选择乘机人页要求传值.
    app.globalData.tempData = that.data.passengerArr;
    //type 0火车票 1机票
    wx.navigateTo({
      url: '../../passenger/passengerSelect/passengerSelect?type=' + 1,
    })
  },
  //选择审批人
  approver: function () {
    var that = this;
    //传已选择审批人数组，，应对方要求所有传值都通过同一个全局对象传递。（app.globalData.tempData）
    app.globalData.tempData = that.data.approveArr;

    wx.navigateTo({
      url: '../../approver/department/department',
    })
  },
  //联系人
  contactPerson: function () {
    var that = this;
    wx.navigateTo({
      url: '../../contactPerson/contactPerson?linkManInfo=' + JSON.stringify(that.data.linkManInfo),
    })

  },
  payType: function (res) {
    var that = this;
    var type = res.currentTarget.dataset.type;
    if (type == 'company') {
      that.setData({
        checkCompany: true,
        checkSelf: false
      })
    } else if (type == 'self') {
      that.setData({
        checkCompany: false,
        checkSelf: true
      })
    }
  },
  //提交订单
  submitOrder: function () {
    var that = this;
    //非空验证
    if (that.data.passengerArr.length == 0) {
      wx.showToast({
        title: '请选择乘客',
      })
      return;
    }
    if (that.data.approveArr.length == 0 && (that.data.showApproveView == true)) {
      wx.showToast({
        title: '请选择审批人',
      })
      return;
    }
    if (that.data.onBusinessReason.length == 0) {
      wx.showToast({
        title: '请填写出差原因',
      })
      return;
    }

    that.showLoading();
    var postData = that.preparePostDic();
    var url = config.getBaseUrl('Train', 'CreateTicketOrder');
    netWork.post(
      url,
      postData,
      function (res) {//success
        wx.hideLoading()
        console.log('order:::');
        console.log(res.data);
        if (res.data.ResponseMetaInfo.StatusCode == '0') {
          //跳转到成功页
          var orderNo = res.data.Data.OrderNo;
          var money = res.data.Data.OrderAmount;
          that.success(orderNo,money);
        }
        else if (res.data.ResponseMetaInfo.StatusCode == '500') {
          wx.showToast({
            title: res.data.ResponseMetaInfo.Reason,
          })
        }else {
          wx.showToast({
            title: res.data.ResponseMetaInfo.Reason,
          })
        }
      },
      function (res) {//fail
        wx.hideLoading()
      }
    )
  },

  
  success: function (orderNo,money) {
    wx.redirectTo({
      url: '../../success/success?orderN=' + orderNo + '&money=' + money + '&paytype=' + 0 + '&resultType=' + 0,
    })
  }
})